package com.sdry.web.controller.lz;

import com.sdry.model.barCodeOperation.BarCodeOperation;
import com.sdry.model.jyy.ReceiveDetailQuality;
import com.sdry.model.llm.BarCode;
import com.sdry.model.llm.DeliveryNode;
import com.sdry.model.lz.*;
import com.sdry.model.zc.ZcMaterielAndTrayEntity;
import com.sdry.model.zc.ZcSysUserEntity;
import com.sdry.service.barCodeOperation.BarCodeOperationService;
import com.sdry.service.jyy.ReceiveDetailService;
import com.sdry.service.llm.CancellingStockService;
import com.sdry.service.lz.CarService;
import com.sdry.service.lz.InventoryService;
import com.sdry.service.lz.MaterielService;
import com.sdry.utils.ResponseUtil;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @ClassName CarCOntroller
 * @Description 车辆信息
 * @Author lz
 * @Date 2019年4月16日 10:02:27
 * @Version 1.0
 */
@Controller
@RequestMapping("/car")
public class CarController {
    public static final Integer AFFECT_ROW = 0;

    @Resource
    CarService carService;
    @Resource
    ReceiveDetailService receiveDetailService;
    @Resource
    BarCodeOperationService barCodeOperationService;
    
    /**
     * 车辆新增
     * @param response
     * @param car
     */
    @RequestMapping("/addCar")
    public void addCar(HttpServletResponse response, Car car){
        Long affectRow = carService.addCar(car);
        try {
            ResponseUtil.write(response, affectRow);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据ID删除该行数据
     * @param response
     * @param idArr
     */
    @RequestMapping("/deleteCarById")
    public void deleteCarById(HttpServletResponse response, @RequestParam("idArr[]") String[] idArr){
        if(idArr.length > 0) {
            for (int i = 0; i < idArr.length; i++) {
                Long affectRow = carService.deleteCarById(Long.parseLong(idArr[i]));
                if (affectRow > AFFECT_ROW) {
                    try {
                        ResponseUtil.write(response, affectRow);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    try {
                        ResponseUtil.write(response, AFFECT_ROW);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    /**
     * 行内编辑车辆表
     * @param response
     */
    @RequestMapping("/updateCar")
    public void updateCar(HttpServletResponse response, Car Car) {
        Long affectRow = carService.updateCar(Car);
        if(affectRow > AFFECT_ROW){
            try {
                ResponseUtil.write(response, affectRow);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            try {
                ResponseUtil.write(response, "");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 分页查询车辆表
     * @param response
     * @param criteria
     */
    @RequestMapping("/queryCarCriteria")
    public void queryCarCriteria(HttpServletResponse response, LzQueryCriteria criteria){
        String keyword01 = criteria.getKeyword01();
        String keyword02 = criteria.getKeyword02();
        if(keyword01 == null){
            keyword01 = "";
        }
        if(keyword02 == null){
            keyword02 = "";
        }
        criteria.setKeyword01(keyword01);
        criteria.setKeyword02(keyword02);
        List<Car> CarList = carService.queryCarCriteria(criteria);
        int count = carService.countCarCriteria(criteria);
        JSONObject jsonObject = new JSONObject();
        JSONArray jsonArray = JSONArray.fromObject(CarList);
        jsonObject.put("code", AFFECT_ROW);
        jsonObject.put("data", jsonArray);
        jsonObject.put("count", count);
        try {
            ResponseUtil.write(response, jsonObject);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    @Resource
	private CancellingStockService cancellingStockService;
    @Resource
	private InventoryService inventoryService;
    @Resource MaterielService materielService;
    /**
     * 根据条码查询该条码是否存在
     * @param response
     * @param beforeCode 原条码
     * @param mcode 产品码 SAP/QAD
     * @param location 库位
     */
    @RequestMapping("/queryCodeExist")
    public void queryCodeExist(HttpServletResponse response, String beforeCode,String mcode,String location, HttpSession session){
    	Long warehouse_id = (Long) session.getAttribute("warehouse_id");
    	int flg = 0;
    	//根据条码查询该条码是否存在
    	CodeMark codeMark = carService.queryCodeExist(beforeCode);
        if (codeMark != null) {
        	CodeMark code = new CodeMark();
        	code.setCode(beforeCode);
        	code.setWarehouse_id(warehouse_id);
        	//库位
        	BarCode bar = cancellingStockService.getLocationByCode(code);
        	//根据条码找到物料ID和批次
        	ReceiveDetailQuality byCode = inventoryService.queryReceiveByCode(beforeCode);
        	if(bar != null && byCode != null && location.equals(bar.getRemark02())){
        		//根据id查物料
        		Materiel materiel = materielService.queryMaterielById(byCode.getMid());
        		if(materiel != null && mcode.equals(materiel.getMateriel_num())){
        			flg = 1;
        		}
        	}
        } 
        try {
        	ResponseUtil.write(response, flg);
        } catch (Exception e) {
        	e.printStackTrace();
        }
    }
    
    
    /**
     * 修改条码
     * @param response
     * @param beforeCode 原条码
     * @param newCode    新条码
     */
    @RequestMapping("/editCode")
    public void editCode(HttpServletResponse response, String beforeCode, String newCode, HttpSession session){
    	Long affact = 0L;
    	int aff = 0;
    	int result = 0;
    	Long uid = 0L;
    	//校验新条码是否已存在
    	int count = carService.checkNewCode(newCode);
    	
    	if(count > 0) {
    		result = -1;
    	}else {
    		ZcSysUserEntity user = (ZcSysUserEntity)session.getAttribute("user");
    		if(user != null){
    			uid = user.getId();
    		}
    		//1.修改lz_codeMark表中的条码
            affact = carService.editCode(beforeCode, newCode);
            //根据原条码查询绑定托盘的信息
            ZcMaterielAndTrayEntity zcMaterielAndTrayEntity = receiveDetailService.queryMaterielTrayByCode(beforeCode);
            //原条码（借用一下字段）
            zcMaterielAndTrayEntity.setSrcRegion(beforeCode);
            //新条码
            zcMaterielAndTrayEntity.setTargetRegion(newCode);
            
            //2.修改zc_materiel_tray表中的条码
            aff = carService.updateCodeByid(zcMaterielAndTrayEntity);
            
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String time = format.format(new Date());
			ReceiveDetailQuality byCode = inventoryService.queryReceiveByCode(newCode);
			BarCodeOperation bar = new BarCodeOperation();
			BarCodeOperation bar2 = new BarCodeOperation();
			if(byCode != null){
				bar.setBatch(byCode.getPici());
				bar.setMaterielId(byCode.getMid());
				bar2.setBatch(byCode.getPici());
				bar2.setMaterielId(byCode.getMid());
			}
			bar.setBarCode(beforeCode);
			bar.setOperator(uid);
			bar.setOperatingTime(time);
			bar.setType("调账前条码");
			bar2.setBarCode(newCode);
			bar2.setOperator(uid);
			bar2.setOperatingTime(time);
			bar2.setType("调账后条码");
            
            if (affact > 0 && aff > 0) {
            	bar.setResult("成功");
            	bar2.setResult("成功");
            	result = 1;
            } else {
            	bar.setResult("失败");
            	bar2.setResult("失败");
            	result = 0;
            }
            barCodeOperationService.insert(bar);
            barCodeOperationService.insert(bar2);
    	}
        
        try {
			ResponseUtil.write(response, result);
		} catch (Exception e) {
			e.printStackTrace();
		}
    }
    
  //=======================车辆油耗管理==========================
    /**
     * 接收APP传递的经纬度
     * @param response
     * @param longitude 经度
     * @param latitude  纬度
     * @param deliverId 配送单id
     */
    @RequestMapping("/receiveVehicleTransInfo")
    public void receiveVehicleTransInfo(HttpServletResponse response, String longitude,
                                        String latitude, String deliverId){
        VehicleTransInfo vehicleTransInfo = new VehicleTransInfo();
        vehicleTransInfo.setLongitude(longitude);
        vehicleTransInfo.setLatitude(latitude);
        vehicleTransInfo.setDeliverId(deliverId);
        Long rowcount = carService.receiveVehicleTransInfo(vehicleTransInfo);
        JSONObject jsonObject = new JSONObject();
        if(rowcount > AFFECT_ROW){
            jsonObject.put("status", "1");
            jsonObject.put("data", "查询数据成功");
            try {
                ResponseUtil.write(response, jsonObject);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            jsonObject.put("status", "0");
            jsonObject.put("message", "查询数据为空");
            try {
                ResponseUtil.write(response, jsonObject);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 根据出库单id查询车辆的经纬度
     * @param response
     * @param outstock_order_id 出库单id
     */
    @RequestMapping("/queryVehicleTransInfoByOutStockId")
    public void queryVehicleTransInfoByOutStockId(HttpServletResponse response, String outstock_order_id){
        List<VehicleTransInfo> vehicleTransInfoList = carService.queryVehicleTransInfoByOutStockId(outstock_order_id);
        JSONArray jsonArray = JSONArray.fromObject(vehicleTransInfoList);
        if (vehicleTransInfoList.size() > 0) {
            try {
                ResponseUtil.write(response, jsonArray);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            try {
                ResponseUtil.write(response, "0");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 根据出库单id查询已完成的车辆的经纬度
     * @param response
     * @param outstock_order_id 出库单id
     */
    @RequestMapping("/queryVehicleTransInfoByOutStockId2")
    public void queryVehicleTransInfoByOutStockId2(HttpServletResponse response, String outstock_order_id){
        List<VehicleTransInfo> vehicleTransInfoList = carService.queryVehicleTransInfoByOutStockId2(outstock_order_id);
        JSONArray jsonArray = JSONArray.fromObject(vehicleTransInfoList);
        if (vehicleTransInfoList.size() > 0) {
            try {
                ResponseUtil.write(response, jsonArray);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            try {
                ResponseUtil.write(response, null);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 查询所有的出库单
     * @param response
     */
    @RequestMapping("/queryDeliveryNodeByStatus")
    public void queryDeliveryNodeByStatus(HttpServletResponse response){
        //1.查询所有配送单
        List<DeliveryNode> deliveryNodeList = carService.queryDeliveryNodeByStatus();
        for (DeliveryNode deliveryNode: deliveryNodeList) {
            //2.查询该配送单下的所有出库单
            List<OutStockOrder> outStockOrderList = carService.queryOutStockStockOrderByDeliveryNodeId(deliveryNode.getId());
            for (OutStockOrder outStockOrder: outStockOrderList) {
                if (outStockOrder.getStatus() == 1) {
                    //如果都为1，则配送单状态为未出发
                    deliveryNode.setNumber(deliveryNode.getNumber() + "【未出发】");
                } else if (outStockOrder.getStatus() == 4) {
                    //如果都为4，则配送单状态为配送中
                    deliveryNode.setNumber(deliveryNode.getNumber() + "【配送中】");
                } else {
                    //如果都为其他，则配送单状态为已收货
                    deliveryNode.setNumber(deliveryNode.getNumber() + "【已收货】");
                }
            }
        }
        JSONArray jsonArray = JSONArray.fromObject(deliveryNodeList);
        if (deliveryNodeList.size() > 0) {
            try {
                ResponseUtil.write(response, jsonArray);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            try {
                ResponseUtil.write(response, null);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 查询已配送完成的出库单
     * @param response
     */
    @RequestMapping("/queryDeliveryNodeByStatus2")
    public void queryDeliveryNodeByStatus2(HttpServletResponse response){
        List<DeliveryNode> resultEntityList = carService.queryDeliveryNodeByStatus2();
        JSONArray jsonArray = JSONArray.fromObject(resultEntityList);
        if (resultEntityList.size() > 0) {
            try {
                ResponseUtil.write(response, jsonArray);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            try {
                ResponseUtil.write(response, null);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 根据出库单号查询对应的车牌号
     * @param response
     * @param id 配送单id
     */
    @RequestMapping("/queryPlateByOutStockId")
    public void queryPlateByOutStockId(HttpServletResponse response, String id) {
        List<String> resultEntityList = carService.queryPlateByOutStockId(id);
        JSONArray jsonArray = JSONArray.fromObject(resultEntityList);
        if (resultEntityList.size() > 0) {
            try {
                ResponseUtil.write(response, jsonArray);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            try {
                ResponseUtil.write(response, null);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 查询未出库的出库单
     * @param response
     */
    @RequestMapping("/queryOutStockOrderByStatusForPDA")
    public void queryOutStockOrderByStatusForPDA(HttpServletResponse response){
        List<LoadingAppEntity> loadingAppEntityList = carService.queryOutStockOrderByStatusForPDA();
        JSONObject jsonObject = new JSONObject();
        if(loadingAppEntityList.size() > AFFECT_ROW){
            jsonObject.put("status", "1");
            jsonObject.put("data", loadingAppEntityList);
            try {
                ResponseUtil.write(response, jsonObject);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            jsonObject.put("status", "0");
            jsonObject.put("message", "查询数据为空");
            try {
                ResponseUtil.write(response, jsonObject);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /*____________________________________________________*/

    /**
     * 车辆油耗新增
     * @param response
     * @param vehicleFuel
     */
    @RequestMapping("/addVehicleFuel")
    public void addVehicleFuel(HttpServletResponse response, VehicleFuel vehicleFuel){
        Long affectRow = carService.addVehicleFuel(vehicleFuel);
        try {
            ResponseUtil.write(response, affectRow);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据ID删除该行数据
     * @param response
     * @param idArr
     */
    @RequestMapping("/deleteVehicleFuelId")
    public void deleteVehicleFuelId(HttpServletResponse response, @RequestParam("idArr[]") String[] idArr){
        if(idArr.length > 0) {
            for (int i = 0; i < idArr.length; i++) {
                Long affectRow = carService.deleteVehicleFuelById(Long.parseLong(idArr[i]));
                if (affectRow > AFFECT_ROW) {
                    try {
                        ResponseUtil.write(response, affectRow);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    try {
                        ResponseUtil.write(response, AFFECT_ROW);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    /**
     * 行内编辑车辆表
     * @param response
     */
    @RequestMapping("/updateVehicleFuel")
    public void updateVehicleFuel(HttpServletResponse response, VehicleFuel vehicleFuel) {
        Long affectRow = carService.updateVehicleFuel(vehicleFuel);
        if(affectRow > AFFECT_ROW){
            try {
                ResponseUtil.write(response, affectRow);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            try {
                ResponseUtil.write(response, "");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 分页查询车辆表
     * @param response
     * @param criteria
     */
    @RequestMapping("/queryVehicleFuelCriteria")
    public void queryVehicleFuelCriteria(HttpServletResponse response, LzQueryCriteria criteria){
        String keyword01 = criteria.getKeyword01();
        String keyword02 = criteria.getKeyword02();
        if(keyword01 == null){
            keyword01 = "";
        }
        if(keyword02 == null){
            keyword02 = "";
        }
        criteria.setKeyword01(keyword01);
        criteria.setKeyword02(keyword02);
        List<Car> CarList = carService.queryVehicleFuelCriteria(criteria);
        int count = carService.countVehicleFuelCriteria(criteria);
        JSONObject jsonObject = new JSONObject();
        JSONArray jsonArray = JSONArray.fromObject(CarList);
        jsonObject.put("code", AFFECT_ROW);
        jsonObject.put("data", jsonArray);
        jsonObject.put("count", count);
        try {
            ResponseUtil.write(response, jsonObject);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
